<template>
    <div class="department-management">
      <!-- 顶部操作栏 -->
      <div class="top-bar">
        <el-input
          v-model="searchKey"
          placeholder="请输入部门编码、名称"
          style="width: 220px; margin-right: 10px"
          clearable
        />
        <el-checkbox v-model="showDisabled">显示禁用部门</el-checkbox>
        <el-button type="primary" @click="openAddDeptDialog">新增</el-button>
        <el-button @click="handleExport">导出</el-button>
        <el-button type="success" @click="handleEnable">启用</el-button>
        <el-button type="danger" @click="handleDisable">禁用</el-button>
        <el-button type="danger" @click="handleDelete">删除</el-button>
      </div>
  
      <!-- 左侧分类树 + 右侧部门列表 -->
      <div class="content">
        <!-- 左侧分类树 -->
        <div class="left-panel">
          <el-input
            v-model="categorySearch"
            placeholder="请输入分类名称"
            style="margin-bottom: 10px"
            clearable
          />
          <el-tree
            ref="deptCategoryTree"
            :data="categoryList"
            :props="categoryProps"
            :filter-node-method="filterCategory"
            default-expand-all
            @node-click="handleCategoryClick"
          >
            <template #default="{ node }">
              <span>{{ node.label }}</span>
              <!-- 分类操作按钮 -->
              <span class="category-actions">
                <el-icon @click="openAddCategoryDialog(node)"><Plus /></el-icon>
                <el-icon @click="openEditCategoryDialog(node)"><Edit /></el-icon>
                <el-icon @click="handleDeleteCategory(node)" style="color: red"><Delete /></el-icon>
              </span>
            </template>
          </el-tree>
        </div>
  
        <!-- 右侧部门列表 -->
        <div class="right-panel">
          <el-table
            :data="filteredDepts"
            border
            style="width: 100%"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column label="操作" width="100">
              <template #default="scope">
                <el-button
                  type="text"
                  icon="el-icon-edit"
                  @click="openEditDeptDialog(scope.row)"
                >编辑</el-button>
              </template>
            </el-table-column>
            <el-table-column prop="deptCode" label="部门编号" width="120" />
            <el-table-column prop="deptName" label="部门名称" />
            <el-table-column prop="deptCategory" label="部门分类" />
            <el-table-column prop="responsiblePerson" label="负责人" />
            <el-table-column prop="remark" label="备注" />
            <el-table-column label="状态" width="100">
              <template #default="scope">
                <el-switch
                  v-model="scope.row.status"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                  @change="handleStatusChange(scope.row)"
                />
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
  
      <!-- 新增部门弹窗（图2） -->
      <el-dialog title="新增部门" v-model="addDeptVisible">
        <el-form :model="newDept" label-width="100px" :rules="deptRules" ref="deptForm">
          <el-form-item label="部门编号" prop="deptCode">
            <el-input v-model="newDept.deptCode" />
          </el-form-item>
          <el-form-item label="部门名称" prop="deptName">
            <el-input v-model="newDept.deptName" />
          </el-form-item>
          <el-form-item label="部门分类" prop="deptCategory">
            <el-select v-model="newDept.deptCategory" placeholder="请选择">
              <el-option
                v-for="cat in categoryListFlat"
                :key="cat.id"
                :label="cat.label"
                :value="cat.label"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="负责人" prop="responsiblePerson">
            <el-input v-model="newDept.responsiblePerson" />
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="newDept.remark" type="textarea" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="addDeptVisible = false">取消</el-button>
            <el-button type="primary" @click="saveDept">保存</el-button>
            <el-button type="primary" @click="saveAndAddNew">保存并新增</el-button>
          </span>
        </template>
      </el-dialog>
  
      <!-- 编辑部门弹窗 -->
      <el-dialog title="编辑部门" v-model="editDeptVisible">
        <el-form :model="editDeptForm" label-width="100px" :rules="deptRules" ref="editDeptForm">
          <el-form-item label="部门编号" prop="deptCode">
            <el-input v-model="editDeptForm.deptCode" />
          </el-form-item>
          <el-form-item label="部门名称" prop="deptName">
            <el-input v-model="editDeptForm.deptName" />
          </el-form-item>
          <el-form-item label="部门分类" prop="deptCategory">
            <el-select v-model="editDeptForm.deptCategory" placeholder="请选择">
              <el-option
                v-for="cat in categoryListFlat"
                :key="cat.id"
                :label="cat.label"
                :value="cat.label"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="负责人" prop="responsiblePerson">
            <el-input v-model="editDeptForm.responsiblePerson" />
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="editDeptForm.remark" type="textarea" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="editDeptVisible = false">取消</el-button>
            <el-button type="primary" @click="saveEditDept">保存</el-button>
          </span>
        </template>
      </el-dialog>
  
      <!-- 新增部门分类弹窗（图3） -->
      <el-dialog title="新增部门分类" v-model="addCategoryVisible">
        <el-form :model="newCategoryForm" label-width="100px" :rules="categoryRules" ref="categoryForm">
          <el-form-item label="分类名称" prop="categoryName">
            <el-input v-model="newCategoryForm.categoryName" />
          </el-form-item>
          <el-form-item label="上级分类" prop="parentCategory">
            <el-select v-model="newCategoryForm.parentCategory" placeholder="请选择">
              <el-option
                v-for="cat in categoryListFlat"
                :key="cat.id"
                :label="cat.label"
                :value="cat.label"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="addCategoryVisible = false">取消</el-button>
            <el-button type="primary" @click="saveCategory">保存</el-button>
          </span>
        </template>
      </el-dialog>
  
      <!-- 编辑部门分类弹窗 -->
      <el-dialog title="编辑部门分类" v-model="editCategoryVisible">
        <el-form :model="editCategoryForm" label-width="100px" :rules="categoryRules" ref="editCategoryForm">
          <el-form-item label="分类名称" prop="categoryName">
            <el-input v-model="editCategoryForm.categoryName" />
          </el-form-item>
          <el-form-item label="上级分类" prop="parentCategory">
            <el-select v-model="editCategoryForm.parentCategory" placeholder="请选择">
              <el-option
                v-for="cat in categoryListFlat"
                :key="cat.id"
                :label="cat.label"
                :value="cat.label"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="editCategoryVisible = false">取消</el-button>
            <el-button type="primary" @click="saveEditCategory">保存</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script setup>
  import { ref, computed, watch, getCurrentInstance } from 'vue';
  import {
    ElTable,
    ElTableColumn,
    ElInput,
    ElButton,
    ElCheckbox,
    ElTree,
    ElDialog,
    ElForm,
    ElFormItem,
    ElSelect,
    ElOption,
    ElSwitch,
    ElIcon,
    ElMessageBox,
    ElMessage,
  } from 'element-plus';
  import { Plus, Edit, Delete } from '@element-plus/icons-vue';
  
  // 模拟初始数据
  const categoryList = ref([
    {
      id: 1,
      label: '全部',
      children: [
        { id: 2, label: '未分类' },
      ],
    },
  ]);
  const deptList = ref([
    {
      deptCode: '000001',
      deptName: '总经办',
      deptCategory: '未分类',
      responsiblePerson: '',
      remark: '',
      status: true,
    },
    {
      deptCode: '999',
      deptName: '某某某科技有限公司',
      deptCategory: '未分类',
      responsiblePerson: '',
      remark: '',
      status: true,
    },
    {
      deptCode: '888',
      deptName: '某某科技公司',
      deptCategory: '未分类',
      responsiblePerson: '',
      remark: '',
      status: true,
    },
    {
      deptCode: '2',
      deptName: '销售',
      deptCategory: '未分类',
      responsiblePerson: '',
      remark: '',
      status: true,
    },
  ]);
  
  // 响应式数据
  const searchKey = ref(''); // 部门搜索关键词
  const showDisabled = ref(false); // 是否显示禁用部门
  const categorySearch = ref(''); // 分类搜索关键词
  const selectedDepts = ref([]); // 表格选中项
  const addDeptVisible = ref(false); // 新增部门弹窗
  const editDeptVisible = ref(false); // 编辑部门弹窗
  const addCategoryVisible = ref(false); // 新增分类弹窗
  const editCategoryVisible = ref(false); // 编辑分类弹窗
  const newDept = ref({}); // 新增部门表单
  const editDeptForm = ref({}); // 编辑部门表单
  const newCategoryForm = ref({}); // 新增分类表单
  const editCategoryForm = ref({}); // 编辑分类表单
  const selectedCategory = ref(null); // 当前选中分类
  const { proxy } = getCurrentInstance();
  
  // 分类树配置
  const categoryProps = {
    children: 'children',
    label: 'label',
  };
  
  // 表单验证规则
  const deptRules = {
    deptCode: [{ required: true, message: '请输入部门编号', trigger: 'blur' }],
    deptName: [{ required: true, message: '请输入部门名称', trigger: 'blur' }],
    deptCategory: [{ required: true, message: '请选择部门分类', trigger: 'change' }],
  };
  const categoryRules = {
    categoryName: [{ required: true, message: '请输入分类名称', trigger: 'blur' }],
    parentCategory: [{ required: true, message: '请选择上级分类', trigger: 'change' }],
  };
  
  // 扁平化分类（用于下拉选择）
  const categoryListFlat = computed(() => {
    const flat = [];
    function traverse(list) {
      list.forEach((item) => {
        flat.push(item);
        if (item.children && item.children.length > 0) {
          traverse(item.children);
        }
      });
    }
    traverse(categoryList.value);
    return flat;
  });
  
  // 过滤分类（搜索功能）
  const filterCategory = (value, node) => {
    return node.label.includes(value);
  };
  
  // 监听分类搜索，触发树过滤
  watch(categorySearch, (val) => {
    const tree = proxy?.$refs.deptCategoryTree;
    if (tree) {
      tree.filter(val);
    }
  });
  
  // 选中分类
  const handleCategoryClick = (node) => {
    selectedCategory.value = node;
  };
  
  // 打开新增部门弹窗
  const openAddDeptDialog = () => {
    newDept.value = {
      deptCategory: '未分类', // 默认分类
      status: true, // 默认启用
    };
    addDeptVisible.value = true;
  };
  
  // 保存部门
  const saveDept = () => {
    proxy.$refs.deptForm.validate((valid) => {
      if (valid) {
        deptList.value.push({...newDept.value });
        addDeptVisible.value = false;
        ElMessage.success('部门保存成功！');
      } else {
        ElMessage.error('请完善表单信息！');
      }
    });
  };
  
  // 保存并新增
  const saveAndAddNew = () => {
    saveDept();
    newDept.value = {
      deptCategory: '未分类',
      status: true,
    };
    addDeptVisible.value = true;
  };
  
  // 打开编辑部门弹窗
  const openEditDeptDialog = (row) => {
    editDeptForm.value = {...row };
    editDeptVisible.value = true;
  };
  
  // 保存编辑部门
  const saveEditDept = () => {
    proxy.$refs.editDeptForm.validate((valid) => {
      if (valid) {
        const index = deptList.value.findIndex((item) => item.deptCode === editDeptForm.value.deptCode);
        if (index!== -1) {
          deptList.value[index] = {...editDeptForm.value };
        }
        editDeptVisible.value = false;
        ElMessage.success('部门编辑成功！');
      } else {
        ElMessage.error('请完善表单信息！');
      }
    });
  };
  
  // 打开新增分类弹窗
  const openAddCategoryDialog = (parentNode) => {
    newCategoryForm.value = {
      parentCategory: parentNode? parentNode.label : '全部',
    };
    addCategoryVisible.value = true;
  };
  
  // 保存分类
  const saveCategory = () => {
    proxy.$refs.categoryForm.validate((valid) => {
      if (valid) {
        const parentNode = categoryList.value.find(
          (item) => item.label === newCategoryForm.value.parentCategory
        );
        if (parentNode) {
          const newCat = {
            id: Date.now(),
            label: newCategoryForm.value.categoryName,
            children: [],
          };
          if (parentNode.children) {
            parentNode.children.push(newCat);
          } else {
            parentNode.children = [newCat];
          }
        }
        addCategoryVisible.value = false;
        ElMessage.success('分类保存成功！');
      } else {
        ElMessage.error('请完善表单信息！');
      }
    });
  };
  
  // 打开编辑分类弹窗
  const openEditCategoryDialog = (node) => {
    editCategoryForm.value = {
      categoryName: node.label,
      parentCategory: node.parent? node.parent.label : '全部',
    };
    editCategoryVisible.value = true;
  };
  
  // 保存编辑分类
  const saveEditCategory = () => {
    proxy.$refs.editCategoryForm.validate((valid) => {
      if (valid) {
        const targetNode = findCategoryNode(categoryList.value, editCategoryForm.value.id);
        const parentNode = categoryList.value.find(
          (item) => item.label === editCategoryForm.value.parentCategory
        );
        if (targetNode && parentNode) {
          // 更新分类名称
          targetNode.label = editCategoryForm.value.categoryName;
          // 调整父级
          const oldParent = targetNode.parent;
          if (oldParent && oldParent.children) {
          const index = oldParent.children.findIndex((item) => item.id === targetNode.id);
          if (index !== -1) {
            oldParent.children.splice(index, 1);
          }
        }
        if (!parentNode.children) {
          parentNode.children = [];
        }
        parentNode.children.push(targetNode);
      }
      editCategoryVisible.value = false;
      ElMessage.success('分类更新成功！');
    } else {
      ElMessage.error('请完善表单信息！');
    }
  });
};

// 查找分类节点
const findCategoryNode = (list, id) => {
  for (const item of list) {
    if (item.id === id) {
      return item;
    }
    if (item.children && item.children.length > 0) {
      const found = findCategoryNode(item.children, id);
      if (found) {
        return found;
      }
    }
  }
  return null;
};

// 删除分类
const handleDeleteCategory = (node) => {
  if (node.id === 1) {
    ElMessage.warning('"全部"分类不能删除！');
    return;
  }
  
  // 检查是否有子分类
  if (node.children && node.children.length > 0) {
    ElMessage.warning('请先删除该分类下的所有子分类！');
    return;
  }
  
  // 检查是否有部门使用该分类
  const hasDepts = deptList.value.some(
    (dept) => dept.deptCategory === node.label
  );
  
  if (hasDepts) {
    ElMessage.warning('该分类下有部门，不能删除！');
    return;
  }
  
  ElMessageBox.confirm(
    `确定要删除分类"${node.label}"吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    const parent = node.parent;
    if (parent && parent.children) {
      const index = parent.children.findIndex((item) => item.id === node.id);
      if (index !== -1) {
        parent.children.splice(index, 1);
      }
    }
    ElMessage.success('分类删除成功！');
  }).catch(() => {
    // 取消操作
  });
};

// 启用选中的部门
const handleEnable = () => {
  if (selectedDepts.value.length === 0) {
    ElMessage.warning('请先选择要启用的部门！');
    return;
  }
  
  selectedDepts.value.forEach((dept) => {
    dept.status = true;
  });
  
  selectedDepts.value = [];
  ElMessage.success('部门启用成功！');
};

// 禁用选中的部门
const handleDisable = () => {
  if (selectedDepts.value.length === 0) {
    ElMessage.warning('请先选择要禁用的部门！');
    return;
  }
  
  selectedDepts.value.forEach((dept) => {
    dept.status = false;
  });
  
  selectedDepts.value = [];
  ElMessage.success('部门禁用成功！');
};

// 删除选中的部门
const handleDelete = () => {
  if (selectedDepts.value.length === 0) {
    ElMessage.warning('请先选择要删除的部门！');
    return;
  }
  
  ElMessageBox.confirm(
    `确定要删除选中的${selectedDepts.value.length}个部门吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    const codes = selectedDepts.value.map((dept) => dept.deptCode);
    deptList.value = deptList.value.filter((dept) => !codes.includes(dept.deptCode));
    selectedDepts.value = [];
    ElMessage.success('部门删除成功！');
  }).catch(() => {
    // 取消操作
  });
};

// 导出部门数据
const handleExport = () => {
  ElMessage.info('导出功能开发中...');
};

// 表格选择变化
const handleSelectionChange = (rows) => {
  selectedDepts.value = rows;
};

// 部门状态变更
const handleStatusChange = (row) => {
  ElMessage.info(`【${row.deptName}】状态变更为：${row.status ? '启用' : '禁用'}`);
};

// 计算过滤后的部门列表
const filteredDepts = computed(() => {
  if (!searchKey.value && !selectedCategory.value) {
    return showDisabled.value
      ? deptList.value
      : deptList.value.filter((dept) => dept.status === true);
  }
  
  let result = deptList.value;
  
  // 按搜索关键词过滤
  if (searchKey.value) {
    const keyword = searchKey.value.toLowerCase();
    result = result.filter(
      (dept) =>
        dept.deptCode.toLowerCase().includes(keyword) ||
        dept.deptName.toLowerCase().includes(keyword)
    );
  }
  
  // 按分类过滤
  if (selectedCategory.value && selectedCategory.value.label !== '全部') {
    result = result.filter((dept) => dept.deptCategory === selectedCategory.value.label);
  }
  
  // 按状态过滤
  if (!showDisabled.value) {
    result = result.filter((dept) => dept.status === true);
  }
  
  return result;
});
</script>

<style scoped>
/* 基本布局样式 */
.department-management {
  display: flex;
  flex-direction: column;
  height: 100vh;
}

.top-bar {
  display: flex;
  align-items: center;
  padding: 10px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
}

.content {
  display: flex;
  flex: 1;
  overflow: hidden;
}

.left-panel {
  width: 250px;
  border-right: 1px solid #e4e7ed;
  padding: 10px;
  overflow-y: auto;
}

.right-panel {
  flex: 1;
  padding: 10px;
  overflow-y: auto;
}

/* 分类树样式 */
.category-actions {
  margin-left: 10px;
  opacity: 0;
  transition: opacity 0.3s;
}

.el-tree-node:hover .category-actions {
  opacity: 1;
}

/* 弹窗样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>